package com.macrounion.atv.processor;

import javax.annotation.PostConstruct;

import org.joda.time.LocalDate;
import org.springframework.stereotype.Component;

import com.macrounion.atv.service.entity.Reg;
import com.macrounion.atv.service.service.RegService;
import com.macrounion.base.processor.BaseProcessor;
import com.macrounion.base.service.exception.BusinessException;
import com.macrounion.base.service.utils.LicenseDto;
import com.macrounion.base.service.utils.SnHelper;

@Component
public class RegProcessor extends BaseProcessor<Reg, Reg, RegService, Reg> {
	private LocalDate registEndDate = null;
	private LicenseDto licenseDto ;
	
	
	@PostConstruct
	public void init() {
		Reg registered = this.service.selectByRegId(getRegId());
		if(registered!=null){
			decryptRegistCode(registered.getRegcode());
		}
		else{
			licenseDto = new LicenseDto();
		}
	}
	
	
	/**
	 * 计算注册使用截止日期
	 */
	private void decryptRegistCode(String code){
		licenseDto = SnHelper.decrypt(code);
		registEndDate = SnHelper.getRegistEndDate(licenseDto);
		if(licenseDto==null)
			licenseDto = new LicenseDto();
	}
	/**
	 * 注册信息
	 * @return
	 */
	public boolean canUse() {
		if(registEndDate!=null)
			return registEndDate.isAfter(LocalDate.now());
		return false;
	}


	@Override
	public Reg save(Reg reqDto) {
		Reg reg = super.save(reqDto);
		decryptRegistCode(reg.getRegcode());
		return reg;
	}

	public String getRegId() {
		String key = "";
		try {
			key = SnHelper.getJMac();
		} catch (Exception e) {
			throw new BusinessException(101, "请先连接网络");
		}
		return key;
	}

	public Reg getReg() {
		Reg resp = new Reg();
		String key = getRegId();
		resp = this.service.selectByRegId(key);
		if(resp != null)
			return resp;
		resp = new Reg();
		resp.setKeys(key);
		return resp;
	}
}